<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>待办事项 - TodoList</title>
		<style type="text/css"></style>
	</head>
	<body>
		<div id="app">
			<h2>{{title}}</h2>
			<input type="text" @keydown.enter="insert" v-model="msg" />
			<button type="button" @click="search">搜索</button>
			<p><input type="checkbox" v-model="allSelect" />全选</p>
			<ul>
				<li v-for="item in searchList" :key="item.id">
					<input type="checkbox" v-model="item.select" />
					<input v-if="item.state" type="text" v-model="str" @keydown.enter="ok(item.id)" @keydown.esc="esc(item.id)"/>
					<span @click="update(item.id)" v-else>{{item.msg}}</span>
					<!-- 删除功能，永远存在 -->
					<button type="button" @click="del(item.id)">删除</button>
				</li>
			</ul>
		</div>
	</body>
	<script src="../vue.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		
		new Vue({
			el:"#app",
			data:{
				title:"待办事项",
				list:[],
				msg:"",
				start:0,
				str:"",
				searchStr:""	// 搜索关键字
			},
			computed:{
				allSelect:{
					get(){
						return this.list.every(val=>{
							return val.select;
						})
					},
					set(v){
						this.list.forEach(val=>{
							val.select = v;
						})
					}
				},
				// 定义 搜索结果 计算属性,用作渲染列表的数据
				searchList(){
					// 初始立即计算渲染列表
					return this.list.filter(val=>{
						if(this.searchStr === ""){
							// 如果没有搜索关键字,全部返回
							return true
						}else if(val.msg.includes(this.searchStr)){
							// 如果存在搜索关键字,返回
							return true
						}else{
							// 否则不返回
							return false;
						}
					})
				}
			},
			methods:{
				insert(){
					this.list.push({
						id:this.start++,
						msg:this.msg,
						state:false,
						select:false
					})
					this.msg = "";
				},
				del(id){
					let i = 0;
					this.list.some((val,idx)=>{
						i = idx;
						return val.id === id
					});
					this.list.splice(i,1);
				},
				update(id){
					let i = 0;
					this.list.some((val,idx)=>{
						i = idx;
						return val.id === id;
					})
					this.list[i].state = true;
					this.str = this.list[i].msg;
				},
				ok(id){
					let i = 0;
					this.list.some((val,idx)=>{
						i = idx;
						return val.id === id
					})
					this.list[i].state = false;
					this.list[i].msg = this.str;
				},
				esc(id){
					let i = 0;
					this.list.some((val,idx)=>{
						i = idx;
						return val.id === id
					})
					this.list[i].state = false;
				},
				search(){
					// 搜索后取消选中
					this.allSelect = false;
					// 点击搜索时,记录搜索关键字
					this.searchStr = this.msg
				}
			}
		})
		
	</script>
</html>
